<template>
  <div class="login-dialog">
    <div class="login_el_dialog__body">
      <h3>欢迎访问 Chat BI</h3>
      <el-form
        class="login-form"
        :rules="rule"
        :model="loginForm"
        ref="loginFormRef"
        @keyup.enter="handelLogin"
      >
        <div class="mb-20">
          <el-form-item prop="name">
            <el-input
              size="large"
              class="input-item"
              v-model="loginForm.name"
              placeholder="请输入账号"
            >
            </el-input>
          </el-form-item>
        </div>
        <div style="margin-bottom: 58px">
          <el-form-item prop="password">
            <el-input
              type="password"
              size="large"
              class="input-item"
              v-model="loginForm.password"
              placeholder="请输入密码"
              show-password
              @click.stop
            >
            </el-input>
          </el-form-item>
        </div>
        <el-form-item class="remember-item">
          <el-checkbox v-model="rememberMe">记住密码</el-checkbox>
        </el-form-item>
        <el-button
          size="large"
          type="primary"
          class="w-full btn_login"
          @click="handelLogin"
          :loading="loading"
          >登录</el-button
        >
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { LoginRequest } from '@/api/type/user'
import { useRouter } from 'vue-router'
import useStore from '@/stores'
import { decryptData, encryptData, encryptPassword } from '@/utils/crypto'
import { MsgError } from '@/utils/message'

const { user, agent, dataset } = useStore()
const router = useRouter()

defineOptions({ name: 'IndexLogin' })

const loading = ref<boolean>(false)
const loginFormRef = ref<FormInstance>()
const loginForm = ref<LoginRequest>({
  name: '',
  password: ''
})

const rememberMe = ref(false)
const isCodeDisabled = ref(false)

const rule: any = ref<FormRules<LoginRequest>>({
  name: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

const handelLogin = () => {
  // 清空全局状态管理 分类
  agent.clearCategorizeOptions()
  dataset.clearCategorizeOptions()

  passwordLogin()
}

/**
 * 登录方法
 */
const login = async (data: any) => {
  loading.value = true
  const password = encryptPassword(data.password)
  user
    .login(data.name, password)
    .then((res: any) => {
      // 账号密码登录-记住密码
      if (rememberMe.value) {
        const encrypted = encryptData(loginForm.value.password)
        localStorage.setItem(
          'loginCredentials',
          JSON.stringify({
            name: loginForm.value.name,
            encryptedPwd: encrypted
          })
        )
      } else {
        localStorage.removeItem('loginCredentials')
      }
      if (res) {
        router.push({ name: 'webapp' })
      }
    })
    .catch((err) => {
      MsgError(err.response.data.msg)
    })
    .finally(() => (loading.value = false))
}

/**
 * 通过账号密码登录
 */
const passwordLogin = async () => {
  loading.value = true
  loginFormRef.value
    ?.validate()
    .then(async () => {
      loading.value = true
      // 密码登录
      let data: any = {
        name: loginForm.value.name,
        password: loginForm.value.password
      }
      await login(data)
    })
    .finally(() => {
      loading.value = false
    })
}

const getLocaUserInfo = () => {
  const saved = localStorage.getItem('loginCredentials')
  if (saved) {
    const { name, encryptedPwd } = JSON.parse(saved)
    loginForm.value = {
      name,
      password: decryptData(encryptedPwd)
    }
    rememberMe.value = true
  }
}

onMounted(() => {
  isCodeDisabled.value = true

  getLocaUserInfo()

  nextTick(() => {
    const dom = document.querySelector('.el-input__suffix')
    if (dom) {
      dom.addEventListener('click', (event) => {
        event.preventDefault()
        const input = dom.closest('.el-input')?.querySelector('input')
        if (input) {
          input.setSelectionRange(0, 0)
        }
        return false
      })
    }
  })
})
</script>

<style lang="scss" scope>
.login-dialog {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-color: #fff;

  padding: 0;
  border-radius: 12px;
  .login_el_dialog__body {
    padding: 40px 40px 50px 40px;
    width: 440px;
    position: relative;
    h3 {
      line-height: 36px;
      height: 36px;
      font-size: 24px;
      color: #333;
      margin-bottom: 32px;
    }
    .btn_login {
      height: 40px;
      border-radius: 6px;
    }
  }
}

.login-form {
  .el-input__append {
    padding: 0;
    .el-button {
      width: 100px;
    }
  }
}

/* 记住密码*/
.remember-item {
  bottom: 94px;
  margin-bottom: 0;
  position: absolute;
}

</style>
